package com.we.flink.userlabelplatform.table;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;

public class TableUserCertifyEducation {
    public static final String KFKTABLE = "fdm.hhl01_user_certify_education";
    public static final String QUERYSQL =
            "select uid, "
                    + "if(highest_education is null, -1, highest_education) as highest_education, "
                    + "if(updated_time is null, TIMESTAMP '1970-01-01 08:00:00.000000', updated_time) as updated_time "
                    + "from "
                    + KFKTABLE
                    + " where uid is not null and deleted_time is null";

    public long uid;
    public int highest_education;
    public Timestamp updated_time;

    public static Logger LOG = LoggerFactory.getLogger(TableUserCertifyEducation.class);

    public TableUserCertifyEducation() {}

    public TableUserCertifyEducation(long uid, int highest_education, Timestamp updated_time) {
        this.uid = uid;
        this.highest_education = highest_education;
        this.updated_time = updated_time;
    }

    public static TableUserCertifyEducation init(long uid) {
        return new TableUserCertifyEducation(uid, -1, new Timestamp(0L));
    }

    public long getUid() {
        return uid;
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableUserCertifyEducation.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUserCertifyEducation>> inputStream =
                tableEnv.toRetractStream(tableRes, TableUserCertifyEducation.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableUserCertifyEducation>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableUserCertifyEducation> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagCertifyEdu-filter")
                        .keyBy(
                                new KeySelector<
                                        Tuple2<Boolean, TableUserCertifyEducation>, Long>() {
                                    @Override
                                    public Long getKey(
                                            Tuple2<Boolean, TableUserCertifyEducation> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableUserCertifyEducation>, String>() {
                                    ValueState<TableUserCertifyEducation>
                                            tableUserCertifyEducationVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        tableUserCertifyEducationVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TableUserCertifyEducation>(
                                                                        "TableUserCertifyEducationVState",
                                                                        TableUserCertifyEducation
                                                                                .class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableUserCertifyEducation> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        int highest_education = value.f1.getHighest_education();
                                        Timestamp updated_time = value.f1.getUpdated_time();

                                        TableUserCertifyEducation tmpState =
                                                tableUserCertifyEducationVState.value();
                                        TableUserCertifyEducation curState =
                                                tmpState == null
                                                        ? TableUserCertifyEducation.init(uid)
                                                        : tmpState;

                                        if (curState.updated_time.getTime()
                                                < updated_time.getTime()) {
                                            if (curState.getHighest_education()
                                                    != highest_education) {
                                                curState.highest_education = highest_education;
                                                curState.updated_time = updated_time;
                                                JSONObject jsonObject = new JSONObject();
                                                jsonObject.put("uid", uid);
                                                jsonObject.put(
                                                        "highest_education", highest_education);
                                                out.collect(jsonObject.toString());

                                                tableUserCertifyEducationVState.update(curState);
                                            }
                                        }
                                    }
                                });

        return out;
    }

    public int getHighest_education() {
        return highest_education;
    }

    public Timestamp getUpdated_time() {
        return updated_time;
    }
}
